package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.utils.common.ProtostuffUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanServiceImpl wmNewsAutoScanService;
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //创建文章的对象,设置id,并把这个对象序列化当作参数存储在task中
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        //使用fegin远程调用添加任务的方法
        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }



    /**
     * 消费延迟队列数据,每秒执行一次,精确时间发布
     */
    @Scheduled(fixedRate = 1000)
    @Override
    @SneakyThrows
    @XxlJob("scanNewsByTask")
    public void scanNewsByTask() {
        //根据类型和优先级来消费任务,如果有任务则立即消费
        ResponseResult responseResult = scheduleClient
                .poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                        TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //如果返回成功
        if(responseResult.getCode().equals(200) && responseResult.getData() != null){
            //把数据从json转成task对象,获取参数
            String json_str = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(json_str, Task.class);
            byte[] parameters = task.getParameters();
            //反序列化wmNews对象
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            //拿到id进行扫描
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }

    }
}
